package com.xing.libao.cron;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.SocketTimeoutException;

/**
 * Created with IntelliJ IDEA.
 * User: xingzhe
 * Date: 2015/9/17
 * Time: 10:12
 */
public class AiBJCron {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;

    public AiBJCron() {
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(50);
        cm.setDefaultMaxPerRoute(40);
        httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).build();
    }

    public static void main(String[] args) {
        AiBJCron aiBJCron = new AiBJCron();
        HttpGet get = new HttpGet("http://www.aibj.biz/forum.php?mod=forumdisplay&fid=178");
        aiBJCron.setHeader(get);
//        String result = aiBJCron.html(get,"gbk");
//        if(StringUtils.isNotEmpty(result)) {
//            Document document = Jsoup.parse(result);
//            Elements elements = document.select("form#moderate>table>tbody>tr>td.by>cite");
//            for(Element element:elements){
//                System.out.println(element.getElementsByTag("a").attr("href"));
//                aiBJCron.html(new HttpGet("http://www.aibj.biz/"+element.getElementsByTag("a").attr("href")),"gbk");
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }

        System.out.println(aiBJCron.html(new HttpGet("http://www.aibj.biz/forum.php?mod=forumdisplay&fid=137"), "gbk"));
    }

    private void setHeader(HttpUriRequest request) {
        request.setHeader("Cookie", "nzrE_2132_saltkey=U777GxMh; nzrE_2132_lastvisit=1441526301; nzrE_2132_atarget=1; nzrE_2132_auth=4881uolTydO3w0N0te3V1QTIJS0cHH7waQqXb7rN4L0tJT2LMAr8gWk636IViGNp1FxY34tDyFYSFofg5acLVWf4FqE; nzrE_2132_lastcheckfeed=454217%7C1441529910; nzrE_2132_nofavfid=1; nzrE_2132_seccode=20676.a74c5de307c5d9369d; nzrE_2132_taskdoing_454217=1; nzrE_2132_home_diymode=1; key302=360a7264e2; expire302=1442799233; nzrE_2132_ulastactivity=2899yU3fHS5zHCkJ5qRXqNm84WnV6ptEiS1%2BoolGRHD2PLwWSwKx; nzrE_2132_promotion=190008; nzrE_2132_st_p=454217%7C1442799521%7Cd6aca9564806b4d7b236442ec4e7540a; nzrE_2132_viewid=tid_434072; nzrE_2132_smile=1D1; nzrE_2132_mobile=no; nzrE_2132_lip=111.205.130.62%2C1442799492; nzrE_2132_sendmail=1; nzrE_2132_st_t=454217%7C1442800136%7C6f3d1b6c0cecbbb9238ad220f0d2569b; nzrE_2132_forum_lastvisit=D_63_1442285297D_40_1442564769D_178_1442565928D_42_1442572535D_137_1442800136; nzrE_2132_sid=t3HjSS; nzrE_2132_lastact=1442800137%09home.php%09spacecp; nzrE_2132_checkpm=1; CNZZDATA5331698=cnzz_eid%3D892808252-1441528985-%26ntime%3D1442794971");
        request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        request.setHeader("Accept-Encoding", "gzip, deflate, sdch");
        request.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
        request.setHeader("Host", "www.aibj.biz");
        request.setHeader("Referer", "http://www.aibj.biz/forum.php");
        request.setHeader("Upgrade-Insecure-Requests", "1");
        request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36");
    }

    private String html(HttpUriRequest request, String charset) {
        String content = null;
        try {
            response = httpClient.execute(request);
            if (response.getStatusLine().getStatusCode() != 200) {
                System.out.println("访问网站出错！ code: " + response.getStatusLine().getStatusCode() + " url: " + request.getURI().toString());
                return null;
            } else {
                System.out.println("StatusLine: " + response.getStatusLine().getStatusCode());
            }
            HttpEntity re = response.getEntity();
            content = EntityUtils.toString(re, charset);
            if (!request.isAborted()) {
                request.abort();
            }
            response.close();
        } catch (SocketTimeoutException e) {
            System.out.println("Read timed out!" + request.getURI().toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
}
